package com.hundsun.monitor.client.view;

import java_cup.internal_error;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasAllMouseHandlers;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.MouseWheelEvent;
import com.google.gwt.event.dom.client.MouseWheelHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.hundsun.monitor.client.MyHome;
import com.hundsun.monitor.client.model.Gadget;
import com.hundsun.monitor.client.model.UserPref;

public class GadgetContainerView extends SimplePanel implements HasAllMouseHandlers{
	
	public static interface TitleBarImageBundle extends ClientBundle{

		@Source("maximization.gif")
		public ImageResource closeIcon();

		@Source("maximization.gif")
		public ImageResource  minimize1Icon();

		@Source("maximization.gif")
		public ImageResource  minimize2Icon();

		@Source("maximization.gif")
		public ImageResource refreshIcon();
		
		@Source("maximization.gif")
		public ImageResource maximizationIcon();
		
		@Source("settings.png")
		public ImageResource settingIcon();
		
	}
	
	public static TitleBarImageBundle titleBarImages = GWT.create( TitleBarImageBundle.class );

	private Gadget child;
	private HorizontalPanel titleBar = new HorizontalPanel();
	private VerticalPanel mainLayout = new VerticalPanel();
	private Label title = new Label();
	private Hyperlink edit = new Hyperlink("edit","");
	private ToggleButton minimizeButton = new ToggleButton(new Image(titleBarImages.minimize1Icon()),new Image(titleBarImages.minimize2Icon()));
	private PushButton refreshButton = new PushButton(new Image(titleBarImages.refreshIcon()));
	private PushButton closeButton = new PushButton(new Image(titleBarImages.closeIcon()));
	private FlexTable editPanel = new FlexTable();
	private SimplePanel childContainer = new SimplePanel();
	private Image maxImage = new Image(titleBarImages.maximizationIcon());
	private Image settingImage = new Image(titleBarImages.settingIcon());
    private DecoratedPopupPanel popupPanel = new DecoratedPopupPanel(true);
    private VerticalPanel settingsPanel = new VerticalPanel();
	private boolean open = true;
	private boolean max = false;
	private boolean editopen = false;
	/** Mouse handler registration */
    private HandlerRegistration mouseDownRegistration, mouseUpRegistration,
                    mouseMoveRegistration;
	
	public GadgetContainerView( Gadget c ){
		child = c;
		buildTitleBar();		
		buildMainLayout();
		mainLayout.setWidth("100%");
		setWidget( mainLayout );
		child.refresh();		

		//set style names
		setStyleName("z-GadgetContainer");
		mainLayout.setStyleName("z-GadgetContainerPanel");
		titleBar.setStyleName("z-GadgetContainerTitleBar");
		editPanel.setStyleName("z-GadgetContainerEditPanel");
		title.setStyleName("z-GadgetContainerTitle");
		childContainer.setStyleName("z-GadgetContainerBody");
		maxImage.setStyleName("z-GadgetContainerImage");
		settingImage.setStyleName("z-GadgetContainerImage");
	}
	
	protected void buildMainLayout(){
		mainLayout.add( titleBar );
		if( child.getGadgetClass().getUserPrefsCount() > 0 ){
			mainLayout.add( editPanel );
			editPanel.setWidth("100%");
			buildEditPanel();
		}
		childContainer.setWidget( child );		
		mainLayout.add( childContainer );
	}
	
	protected void buildTitleBar(){
		int column = 0;
//		titleBar.add( minimizeButton );
		titleBar.add( title );
//		titleBar.add( refreshButton );
		if( child.getGadgetClass().getUserPrefsCount() > 0 )
			titleBar.add( edit );
		titleBar.add(settingImage);
		titleBar.add(maxImage);
//		titleBar.add( closeButton );
		titleBar.setCellWidth( title, "100%" );
		titleBar.setWidth("100%");
		title.setWidth("100%");
		title.setText(child.getTitle());
		buildClickListeners();
	}
	
	protected void buildClickListeners(){
		edit.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				toggleEdit();
			}
		});
		refreshButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				child.refresh();
			}
		});
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if( Window.confirm( "Remove "+child.getGadgetClass().getName()+" from your page?") ){
					getParent().removeFromParent();
					child.getGadgetListener().onInterfaceChange();
				}
			}
		});
		minimizeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if( minimizeButton.isDown() )
					child.setVisible( false );
				else
					child.setVisible( true );
				open = !open;
			}
		});
		maxImage.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				DeckPanel dPanel = MyHome.getView().getGadgetTabs().getDeckPanel();
				HorizontalPanel page = (HorizontalPanel)MyHome.getView().getGadgetTabs().getWidget(dPanel.getVisibleWidget());
				int currentIdx = page.getWidgetIndex(child.getParent().getParent().getParent().getParent().getParent());
				if(!max){
					for(int i = 0 ; i < 3 ; i++){
						if(i!=currentIdx){
							page.setCellWidth(page.getWidget(i),"0%");
							page.getWidget(i).setVisible(false);
						}
					}
					FlowPanel flowPanel = ((FlowPanel)page.getWidget(currentIdx));
					int idxOfPanel = flowPanel.getWidgetIndex(child.getParent().getParent().getParent().getParent());
					
					for(int i = 0 ; i < flowPanel.getWidgetCount() ;i++){
						if(i!=idxOfPanel){
							flowPanel.getWidget(i).setVisible(false);
						}
					}
				}else{
					for(int i = 0 ; i < 3 ; i++){
						page.setCellWidth(page.getWidget(i),"33%");
						page.getWidget(i).setVisible(true);
					}
					FlowPanel flowPanel = ((FlowPanel)page.getWidget(currentIdx));
					for(int i = 0 ; i < flowPanel.getWidgetCount() ;i++){
						flowPanel.getWidget(i).setVisible(true);
					}
				}
				max = !max;
			}
		});
	
		settingImage.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				// Reposition the popup relative to the button
	            Widget source = (Widget) event.getSource();
	            int widthScreem = Window.getClientWidth();
	            int heightScreem = Window.getClientHeight();
	            int left = source.getAbsoluteLeft() + 10;
	            int top = source.getAbsoluteTop() + 10;
	            if(left+190>widthScreem){
	            	left = source.getAbsoluteLeft() - 190;
	            }
	            if(top+28>heightScreem){
	            	top = source.getAbsoluteTop() - 28;
	            }
	            System.out.println("left:"+left+",top:"+top);
	            System.out.println(Window.getClientWidth());
	            System.out.println(Window.getClientHeight());
	            popupPanel.setPopupPosition(left, top);
	            popupPanel.setSize("190px", "28px");
	            popupPanel.setStyleName("z-menu");
	            Anchor minimizeAnchor = new Anchor("最小化");
	            Anchor expandAnchor = new Anchor("还原");
	            minimizeAnchor.setStyleName("z-anchor");
	            expandAnchor.setStyleName("z-anchor");
	            settingsPanel.add(minimizeAnchor);
	            settingsPanel.add(expandAnchor);
	            popupPanel.add(settingsPanel);
	            // Show the popup
	            popupPanel.show();

			}
		});
		
	}
	
	protected void buildEditPanel(){
		editPanel.setVisible(editopen);
		editPanel.setStyleName("z-GadgetContainerEditPanel");
		for( int i=0; i<child.getGadgetClass().getUserPrefsCount(); ++i ){
			final UserPref up = child.getGadgetClass().getUserPref(i);
			editPanel.setText(i,0,up.getName()+":");
			Object value = child.getUserPrefValue(up);
			if( value instanceof String ){
				final TextBox editbox = new TextBox();
				editbox.setText((String)value);
				editbox.addChangeListener( new ChangeListener(){
					public void onChange(Widget sender){
						child.setUserPrefValue(up,editbox.getText());
					}
				});
				editPanel.setWidget(i,1,editbox);
				editPanel.getCellFormatter().setWidth(i,1,"100%");
				editbox.setWidth("100%");
			}				
		}
	}
	
	public void toggleEdit(){
		editopen = !editopen;
		editPanel.setVisible(editopen);
		if( !editopen ){
			edit.setText("edit");
			child.refresh();
			child.getGadgetListener().onInterfaceChange();
		}
		else{
			edit.setText("done");
		}
	}

	public Gadget getGadget(){
		return child;
	}

	@Override
	public HandlerRegistration addMouseDownHandler(MouseDownHandler handler) {
		mouseDownRegistration = title.addDomHandler(handler, MouseDownEvent.getType());
		return mouseDownRegistration;
	}

	@Override
	public HandlerRegistration addMouseWheelHandler(MouseWheelHandler handler) {
		return title.addDomHandler(handler, MouseWheelEvent.getType());
	}

	@Override
	public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) {
		return title.addDomHandler(handler, MouseOverEvent.getType());
	}

	@Override
	public HandlerRegistration addMouseUpHandler(MouseUpHandler handler) {
		mouseUpRegistration = title.addDomHandler(handler, MouseUpEvent.getType());
		return mouseUpRegistration;
	}

	@Override
	public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) {
		return title.addDomHandler(handler, MouseOutEvent.getType());
	}

	@Override
	public HandlerRegistration addMouseMoveHandler(MouseMoveHandler handler) {
		this.mouseMoveRegistration = title.addDomHandler(handler, MouseMoveEvent.getType());
		return mouseMoveRegistration;
		
	}
	
	public void removeMouseHandler(){
		mouseMoveRegistration.removeHandler();
		mouseDownRegistration.removeHandler();
		mouseUpRegistration.removeHandler();
	}

}
